/**
 * @Title: DeleteEditText.java
 * @author zengshuai shi
 * @date 2015年8月3日 下午3:07:54
 */
package com.onstar.cn.weight;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.AttributeSet;
import android.widget.EditText;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.animation.Animation;
import android.view.animation.CycleInterpolator;
import android.view.animation.TranslateAnimation;

import com.onstar.cn.common.util.CommonUtil;

/**
 * @author zengshuai shi
 * @ClassName: DeleteEditText
 * @Description: TODO
 * @date 2015年8月3日 下午3:07:54
 */
public class DeleteEditText extends EditText implements OnFocusChangeListener, TextWatcher {
    /**
     * 删除按钮背景图片
     */
    private Drawable deleteBackground;
    /**
     * 是否有焦点
     */
    private boolean hasFoucus;

    /**
     * 是否清空全部
     */
    private boolean isClearAll = false;
    /**
     * 是否显示清除按钮
     */
    private boolean isShowClearBtn = false;

    /**
     * 右键点击事件监听
     */
    private RightKeyOnClickListener rightKeyOnClick;

    /**
     * 文本框文字输入状态 监听
     */
    private OnTextChangeListener onTextChangeListener;

    /**
     * 输入框有焦点且有内容输入 此View才显示
     */
    private View otherView;

    public DeleteEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        // 初始化资源
        init(attrs);
    }

    public DeleteEditText(Context context, AttributeSet attrs) {
        // 必须添加，否则XML中无法定义
        this(context, attrs, android.R.attr.editTextStyle);
    }

    public DeleteEditText(Context context) {
        super(context, null);
    }

    /**
     * @return void
     * @throws
     * @Title: init
     * @Description: 初始化资源
     */
    private void init(AttributeSet attrs) {
        deleteBackground = getCompoundDrawables()[2];
        if (deleteBackground == null) {
            deleteBackground = getResources().getDrawable(R.drawable.weight_edittext_clear_selector);
        }
        deleteBackground.setBounds(0, 0, CommonUtil.dp2px(20, getContext()), CommonUtil.dp2px(20, getContext()));
        // 默认设置隐藏图标
        setDeleteIconVisible(false);
        // 设置焦点改变的监听
        setOnFocusChangeListener(this);
        // 设置输入框里面内容发生改变的监听
        addTextChangedListener(this);

        if (attrs != null) {
            // 对应ATTR
            TypedArray typeArray = getContext().obtainStyledAttributes(attrs, R.styleable.input);
            this.isClearAll = typeArray.getBoolean(R.styleable.input_isClearAll, true);
            this.isShowClearBtn = typeArray.getBoolean(R.styleable.input_isShowClearBtn, true);
            if (!isShowClearBtn) {
                deleteBackground = null;
            }
            // 释放
            typeArray.recycle();
        }
    }

    /**
     * @param visible 是否显示<br>
     * @return void
     * @throws
     * @Title: setDeleteIconVisible
     * @Description: 设置清除图标的显示与隐藏，调用setCompoundDrawables为EditText绘制上去
     */
    public void setDeleteIconVisible(boolean visible) {
        if (otherView != null) {
            if (visible) {
                otherView.setVisibility(View.VISIBLE);
            } else {
                otherView.setVisibility(View.INVISIBLE);
            }
        }
        Drawable right = visible ? deleteBackground : null;
        setCompoundDrawables(getCompoundDrawables()[0], getCompoundDrawables()[1], right, getCompoundDrawables()[3]);
    }

    @Override
    public void afterTextChanged(Editable s) {
        if (onTextChangeListener != null) {
            onTextChangeListener.afterTextChanged(s);
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    /**
     * @return void
     * @throws
     * @Title: isShowPassword
     * @Description: 显示密码 true|false
     */
    public void isShowPassword(boolean isShow) {
        if (isShow) {
            // 显示明文
            this.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        } else {
            // 显示密文
            this.setTransformationMethod(PasswordTransformationMethod.getInstance());
        }
    }

    /**
     * @return boolean
     * @Title: onTouchEvent
     * @Description: 不能直接给EditText设置点击事件，用按下的位置来模拟点击事件
     * @throws?
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP) {
            if (getCompoundDrawables()[2] != null) {
                boolean touchable = event.getX() > (getWidth() - getTotalPaddingRight())
                        && (event.getX() < ((getWidth() - getPaddingRight())));
                if (touchable) {
                    // 如果设置监听，则外部自己实现点击事件响应
                    if (rightKeyOnClick != null) {
                        rightKeyOnClick.click(this);
                    } else {
                        if (isClearAll) {
                            this.setText("");
                        } else {
                            String text = this.getText().toString();
                            text = text.substring(0, text.length() - 1);
                            this.setText(text);
                        }
                    }
                }
            }
        }
        return super.onTouchEvent(event);
    }

    /**
     * @return void
     * @Title: onTextChanged
     * @Description: 当输入框里面内容发生变化的时候回调的方法
     * @throws?
     */
    @Override
    public void onTextChanged(CharSequence s, int start, int count, int after) {
        if (hasFoucus) {
            // 文本框中有值才显示删除图标
            setDeleteIconVisible(s.length() > 0);
        }
        if (onTextChangeListener != null) {
            onTextChangeListener.textChangeListener(this, s);
        }
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        this.hasFoucus = hasFocus;
        if (hasFocus) {
            setDeleteIconVisible(getText().length() > 0);
        } else {
            setDeleteIconVisible(false);
        }
    }

    /**
     * @return void
     * @Title: 显示晃动动画
     * @Description: 显示晃动动画
     * @throws?
     */
    public void setShakeAnimation() {
        this.setAnimation(shakeAnimation(5));
    }

    /**
     * @param isClearAll true|false 是|否
     * @return void
     * @throws
     * @Title: isClearAll
     * @Description: 是否清空全部
     */
    public void isClearAll(boolean isClearAll) {
        this.isClearAll = isClearAll;
    }

    /**
     * @return void
     * @throws
     * @Title: isShowClearBtn
     * @Description: 是否显示清除按钮 true|false return 是|否
     */
    public void isShowClearBtn(boolean isShowClearBtn) {
        this.isShowClearBtn = isShowClearBtn;
    }

    /**
     * @return Animation
     * @Title: shakeAnimation
     * @Description: 晃动动画 counts 晃动次数
     * @throws?
     */
    private Animation shakeAnimation(int counts) {
        Animation translateAnimation = new TranslateAnimation(0, 10, 0, 0);
        translateAnimation.setInterpolator(new CycleInterpolator(counts));
        translateAnimation.setDuration(1000);
        return translateAnimation;
    }

    /**
     * @param true | false return 是|否 <br>
     * @return void
     * @Title: hasFocus
     * @Description: 是否有焦点
     * @throws?
     */
    public void hasFocus(boolean hasFocus) {
        this.hasFoucus = hasFocus;
    }

    /**
     * @Title: clearAll
     * @Description: 清除所有输入内容
     */
    public void clearAll() {
        this.setText("");
    }

    /**
     * @Title: setCheckOkBg
     * @Description: 设置验证通过的背景图片
     */
    public synchronized void setCheckOkBg(int resId) {
        if (resId == 0) {
            setCompoundDrawables(getCompoundDrawables()[0], getCompoundDrawables()[1], getCompoundDrawables()[2],
                    getCompoundDrawables()[3]);
            return;
        }
        Drawable right = getResources().getDrawable(resId);
        if (right == null) {
            return;
        }
        setCompoundDrawables(getCompoundDrawables()[0], getCompoundDrawables()[1], right, getCompoundDrawables()[3]);
    }

    public void setRightKeyOnClick(RightKeyOnClickListener rightKeyOnClick) {
        this.rightKeyOnClick = rightKeyOnClick;
    }

    public void setOnTextChangeListener(OnTextChangeListener onTextChangeListener) {
        this.onTextChangeListener = onTextChangeListener;
    }

    /**
     * @Title: setOtherView
     * @Description: 设置其他View 显示或隐藏
     */
    public void setOtherView(View view) {
        this.otherView = view;
    }

    /**
     * 是否可以点击，重写父类方法，并隐藏清除键
     */
    public void setEnabled(boolean enabled) {
        setDeleteIconVisible(false);
        super.setEnabled(enabled);
    }

    public void removeTextChangedListener() {
        this.removeTextChangedListener(this);
    }

    public interface RightKeyOnClickListener {
        void click(View view);
    }

    public interface OnTextChangeListener {
        void textChangeListener(View view, CharSequence text);

        void afterTextChanged(Editable s);
    }

    public void onDestory() {
        deleteBackground = null;
        // 设置焦点改变的监听
        setOnFocusChangeListener(null);
        // 设置输入框里面内容发生改变的监听
        addTextChangedListener(null);

    }

    public void setClearAll(boolean clearAll) {
        isClearAll = clearAll;
    }

    public void setShowClearBtn(boolean showClearBtn) {
        isShowClearBtn = showClearBtn;
        if (!isShowClearBtn) {
            deleteBackground = null;
        }
    }
}
